<template>
<div>
  <van-nav-bar
      title=""
      left-text="Return"
      left-arrow
      @click-left="tzback()"
  />
<!--  1.连接信息-->
  <div>
    <van-cell-group inset>
      <van-field
          style="border: 1px solid gainsboro"
          v-model="chat.name"
          center
          clearable
          placeholder="请输入昵称"
      >
        <template #button>
          <van-button size="small" type="primary" @click="connect()">连接</van-button>
          <van-button style="margin-left: 1rem" size="small" type="danger" @click="exit()">离开</van-button>
        </template>
      </van-field>
    </van-cell-group>
  </div>
<!--  2.消息区-->
  <div>
    <van-list
        loading="false"
        finished="true"
    >
      <van-row align="center">
        <van-col span="24" v-for="c in chats" :key="c" >

          <div v-if="c.self" style="margin-right:1rem;float: right;margin-top: 0.5rem">
            <label>{{c.msg}}</label>
            <van-image
                round
                style="margin-left: 0.5rem"
                width="30"
                height="30"
                src="https://img0.baidu.com/it/u=1739700300,2615048112&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
            />
          </div>
          <div v-else style="float: left;margin-left: 1rem;margin-top: 0.5rem">
            <label>{{c.msg}}</label>
            <van-image
                round
                style="margin-right: 0.5rem"
                width="30"
                height="30"
                src="https://img1.baidu.com/it/u=3289228421,4132746211&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
            />

          </div>
        </van-col>
      </van-row>
    </van-list>
  </div>
<!--  3.输入聊天内容-->
  <div style="position: absolute;bottom: 0.5rem;width: 100%">
    <van-cell-group inset>
      <van-field
          v-model="chat.msg"
          center
          style="border: 1px solid gainsboro"
          clearable
          placeholder="请输入聊天内容"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendMsg()">发送</van-button>
        </template>
      </van-field>
    </van-cell-group>
  </div>
</div>
</template>

<script>
// 打开一个 web socket
var ws ;
import {Toast} from "vant";
export default {
  name: "ChatZ",
  data(){
    return{
      chat:{
        name:"",
        msg:"",
        ctype:1,
        type:1
      },
      chats:[]
    }
  }
  ,methods:{
    connect(){
      //连接
      //实例化
      ws= new WebSocket("ws://localhost:8081/chatserver/"+this.chat.name);
      ws.onmessage =res=>{//监听 接收消息
        this.chats.push(JSON.parse(res.data));
        console.log(res.data);
      }
    },exit(){
      ws.close();
      Toast('退出成功！');
      this.$router.push({path:"/bath"});
    },
    sendMsg(){
      //发送消息
      ws.send(JSON.stringify(this.chat));
      this.chat.msg="";

    },
    tzback(){
      this.$router.push({path:"/bath"});
    },
  }
}
</script>

<style scoped>

</style>